<!-- 编辑弹窗 -->
<template>
  <ele-modal width="40%" :visible="visible" :close-on-click-modal="true" custom-class="ele-dialog-form"
    :title="isUpdate ? '修改秒杀信息' : '添加秒杀信息'" @update:visible="updateVisible" >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" >
      <el-row :gutter="24">
        <el-col :md="24" :sm="24">
          <el-form-item label="秒杀产品:"  prop="productName">
            <t-select-table ref="select"  v-model="form.productName" :configure="configure" :list="productDatas" max-height="300px" style="width:100%" :isShowPagination="true" @current-change="handleCurrentChange" returnObj @selectChange="selectChangeRow" />
          </el-form-item>
        </el-col>
          <el-col :md="24" :sm="24">
          <el-form-item label="产品规格:" prop="productItemId">
            <el-radio-group style="width:100%"  v-model="form.productItemId" size="mini" placeholder="请输入秒杀产品规格" filterable clearable >
              <el-radio-button v-for="item in productItems" :key="item.id" :label="item.id" :name="item.id" @click.native="clickradio(item.id)" >{{item.name}}</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :md="24" :sm="24">
          <el-form-item label="开始时间:"  prop="spikeSDate" style="width:100%" >
            <el-date-picker style="width:100%"  v-model="form.spikeSDate"  type="datetime" placeholder="选择日期时间"  format="yyyy-MM-dd HH:mm:ss" @change="changesdate"/> 
          </el-form-item>
        </el-col>
        <el-col :md="24" :sm="24">
          <el-form-item label="结束时间:" prop="spikeEDate" style="width:100%"  >
            <el-date-picker  style="width:100%" v-model="form.spikeEDate"  type="datetime" placeholder="选择日期时间" format="yyyy-MM-dd HH:mm:ss"  @change="changeedate"/> 
          </el-form-item>
        </el-col>
          <el-col :md="24" :sm="24">
          <el-form-item label="限购数量:" prop="limitQty"  >
            <el-input v-model="form.limitQty" placeholder="请输入限购数量"   @keyup.native="form.limitQty = form.limitQty.replace(/[^\d.]/g,'');
                        form.limitQty = form.limitQty.replace(/\.{2,}/g,'.');
                        form.limitQty = form.limitQty.replace(/^\./g,'');
                        form.limitQty = form.limitQty.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                        form.limitQty = form.limitQty.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');"/>
          </el-form-item>
        </el-col>
          <el-col :md="24" :sm="24">
          <el-form-item label="单价:"   prop="price" >
            <el-input v-model="form.price" placeholder="请输入单价"   @keyup.native="form.price = form.price.replace(/[^\d.]/g,'');
                        form.price = form.price.replace(/\.{2,}/g,'.');
                        form.price = form.price.replace(/^\./g,'');
                        form.price = form.price.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                        form.price = form.price.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');"/>
          </el-form-item>
        </el-col>
      </el-row>
  </el-form>
  <div slot="footer">
    <el-button @click="updateVisible(false)">取消</el-button>
    <el-button type="primary" :loading="loading" v-if="this.btnindex!='3'" @click="save">
      保存
    </el-button>
  </div>
  </ele-modal>
</template>

<script>
  import moment from "moment";
  import TSelectTable from '@/components/TTable';
  import { QueryProductViewByParams } from '@/api/productmanager/productmanager';
  import { QueryBProductitemByProductId } from '@/api/productmanager/productitemmanager';
  import { AddMSpike,UpdateSpike,QuerySpikeById } from '@/api/salesmanager/spike';

  export default {
    name: 'SpikeEdit',
    components: { TSelectTable},
    props: {
      // 弹窗是否打开
      visible: Boolean,
      // 修改回显的数据
      data: Object,
      //按钮索引
      btnindex:String,
    },
    data() {
      return {
        // 表单数据
        form: {},
        // 表单验证规则
        rules: {
          productName: [{required: true,message: '请输入产品名称',trigger: 'blur'}],
          productItemId: [{required: true,message: '请输入产品规格',trigger: 'blur'}],
          spikeSDate: [{required: true,message: '请输入秒杀开始时间',trigger: 'blur'}],
          spikeEDate: [{required: true,message: '请输入秒杀结束时间',trigger: 'blur'}],
          limitQty: [{required: true,message: '请输入限购数量',trigger: 'blur'}],
          price: [{required: true,message: '请输入单价',trigger: 'blur'}],
        },
        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false,
        //产品
        productDatas:[],
        //当前选择产品规格Id
        productItemId:'',
        //产品规格
        productItems:[],
        // TSelectTable 可搜索表格配置
        configure: {
          columns: 
          [
              { prop: 'code', title: '编号' ,width:'149px' },
              { prop: 'name', title: '名称',width:'149px'  },
              { prop: 'categoriesName', title: '分类' ,width:'149px' },
              { prop: 'brand', title: '品牌' ,width:'149px' },
              { prop: 'unitDesc', title: '单位',width:'149px' },
              { prop: 'saleQty', title: '销量',width:'149px' },
              { prop: 'productItemName', title: '规格',width:'149px' },
          ],
          keywords: {
              label: 'name',
              value: 'code',
          },
          tablePagination: {
              total: 0, // 总数
              currentPage: 1, // 当前页码
              pageSize: 10, // 当前页面大小
          }
        },
      };
    },

    //初始化数据
    mounted(){
      //覆盖基类的上传数量
      this.initData();
    },
    methods: {
      /* 初始化数据 */
      initData(){
        /* 初始配件数据 */
        this.datasource();
      },

      changesdate(e){
        this.form.spikeSDate = moment(e).format('YYYY-MM-DD HH:mm:ss');
      },

      changeedate(e){
        this.form.spikeEDate = moment(e).format('YYYY-MM-DD HH:mm:ss');
      },

      /* 初始配件数据 */
      async datasource(params) {
        //初始化参数
        let conds = {
            pageIndex: 1,
            conditions: {},
            pageSize: this.configure.tablePagination.pageSize,
            orderBys: [{ sort: "createDate", order: 1, }],
        };

        //页码大小
        if(params?.pageindex){
            conds.pageIndex = params.pageindex;
        }

        //关键字查询
        if(params?.where){
           params.conditions.keyword =  this.where.keyword;
        }

        let data = await QueryProductViewByParams(conds);
        this.productDatas = [];
        this.productDatas = data.items;
        this.configure.tablePagination.total = data.totalrecords;
        this.configure.tablePagination.pageSize = data.pagesize;
        this.configure.tablePagination.currentPage = data.currentpage;
      },

      //页码改变
      handleCurrentChange (val) {
        this.datasource({ pageindex: val})
      },
      
      //获取当前选中行
      selectChangeRow(row){
        this.setProductItemProductId(row.id);
      },
      
      //根据产品id查询产品规格
      setProductItemProductId(id){
        QueryBProductitemByProductId(id).then((res)=>{
            this.form.productId = id;
            this.productItems = [];
            res.map(e => {
              this.productItems.push({id:e.id,name:e.itemName})
            });
        });
      },

      clickradio(id){
        this.productItemId = id;
      },

      /* 保存编辑 */
      save() {
       
        //校验必填信息
        this.$refs['form'].validate((valid) => {
          if (!valid) {return false;}
          this.form.productItemId =  this.productItemId;

          this.loading = true;

          const saveOrUpdate = this.isUpdate ? UpdateSpike : AddMSpike;
          saveOrUpdate(this.form)
            .then((msg) => {
              this.loading = false;
              this.$message.success(msg);
              this.updateVisible(false);

              //回调父组件方法
              this.$emit('done');
            })
            .catch((e) => {
              this.loading = false;
              this.$message.error(e.message);
            });
        });
      },

      /* 更新visible */
      updateVisible(value) {
        //更新父组件中的visible的值
        this.$emit('update:visible', value);
      },

      //赋值到页面
      setSkipt(id){
        QuerySpikeById(id).then((res) => {
            this.productItemId  ='';
            this.form = res;
        });
      },
    },

    /* 监听visible属性变化 */
    watch: {
     visible(visible) {
        if (visible) {
          if (this.data && this.data.id){
            //初始化form
            this.form = {};
            this.productItemId  ='';
            this.setSkipt(this.data.id);
            this.setProductItemProductId(this.data.productId);
            this.isUpdate = this.data.id !=null && this.data.id !=undefined;
          } else {
            this.form = {};
            this.isUpdate =false;
            this.productItemId  ='';
            this.productItems = [];
          }
        } else {
          //移除校验结果
            this.$refs['form'].clearValidate();
        }
      }
    }
  };
</script>
